package com.chatplus.application.processor.listener;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.processor.StreamEventSourceListener;
import com.chatplus.application.processor.constant.AIConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import okhttp3.sse.EventSource;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Objects;

/**
 * OpenAI监听器
 */
public class ChatGPTEventSourceListener extends StreamEventSourceListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGPTEventSourceListener.class);
    String reply = "";


    public ChatGPTEventSourceListener(WebSocketSession session, String platform,String prompt) {
        super(session,platform,prompt);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) {
        try {
            if (data.equals("[DONE]")) {
                LOGGER.message("回答完成").info();
                chatAiUtilHandler.saveChatHistory(reply);
                chatAiUtilHandler.sendMessage(AIConstants.END_LABEL);
                return;
            }
            ObjectMapper mapper = new ObjectMapper();
            ChatCompletionResponse completionResponse = mapper.readValue(data, ChatCompletionResponse.class); // 读取Json
            Message delta = completionResponse.getChoices().get(0).getDelta();
            if (Objects.nonNull(delta.getContent())) {
                chatAiUtilHandler.sendMessage(delta.getContent());
                reply += delta.getContent();
            }
        } catch (IOException e) {
            LOGGER.message("输出回答异常").exception(e).error();
            chatAiUtilHandler.sendMessage(AIConstants.END_LABEL);
        }
    }
}
